package exercise;

import java.util.HashMap;
import java.util.Map;

class Solution13 {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> map = new HashMap<>();

        int l = 0, r = 0, ans = 0, kinds = 0, len = fruits.length;

        while (r < len) {
            int in = fruits[r];
            if (map.getOrDefault(in, 0) == 0) {
                kinds++;
            }
            map.put(in, map.getOrDefault(in, 0) + 1);
            while (kinds > 2) {
                int out = fruits[l];
                map.put(out, map.get(out) - 1);
                if (map.get(out) == 0) kinds--;
                l++;
            }
            ans = Math.max(ans, r-l+1);
            r++;
        }
        return ans;
    }
}